package com.sws.orderMS.command.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.sws.orderMS.OrderMSDao;
import com.sws.orderMS.command.UserCommand;
import com.sws.orderMS.pojo.Client;
import com.sws.orderMS.pojo.User;
import com.sws.orderMS.tool.Tool;

public class ModifyCommand extends UserCommand {
	
	public ModifyCommand(User userProfile) {
		super(userProfile);
	}

	@Override
	public void execute() {
		OrderMSDao dao = new OrderMSDao();
		long userId = userProfile.getId();
		Tool.printMsg("====== " + userProfile.getName() + "的个人信息 ======");
		Tool.printMsg("name: " + userProfile.getName());
		Tool.printMsg("email: " + userProfile.getEmail());
		Tool.printMsg("phone: " + userProfile.getPhone());
		Tool.printMsg("address: " + userProfile.getAddress());
		Tool.printMsg("note: " + userProfile.getNote());
		Tool.printMsg("输入quit退出编辑");
		boolean isChanged = false;
		while (true) {
			String editText = Tool.askUserInputNotNull("请选择需要更改的信息: ");
			if (!"name|email|phone|address|note|quit".contains(editText.toLowerCase())) {
				Tool.printMsg("Invalid input!");
				return;
			}
			if ("quit".equalsIgnoreCase(editText)) {
				String confirm = Tool.askUserInputNotNull("确定退出编辑吗？Y|N");
				if ("Y".equalsIgnoreCase(confirm) && isChanged) {
					Tool.printMsg("信息保存成功！");
					break;
				} else if ("N".equalsIgnoreCase(confirm)) {
					continue;
				} else {
					break;
				}
			}
			String editContent = Tool.askUserInputNotNull("请输入要更改的内容: ");
			int affectRows = dao.updateUser(editText, editContent, userId);
			if (affectRows > 0) {
				try {
					String methodName = "set" + editText.substring(0, 1).toUpperCase() + editText.substring(1);
					Method method = Client.class.getMethod(methodName, String.class);
					method.invoke(userProfile, editContent);
					isChanged = true;
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
